package com.wxx.socket.email;

import com.wxx.socket.util.LogUtil;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class Mail163 {

	// 开发者的邮箱，用于发送邮件
	private static final String FROM_EMAIL = "发送邮件的邮箱";
	private static final String FROM_EMAIL_PASSWORD = "发送邮件的邮箱的密码";
	private static final String EMAIL_HOST = "smtp.163.com";

	public static void sendEmail(String toEmail, String subject, String content) {
		Properties props = new Properties();
		props.put("mail.smtp.host", EMAIL_HOST);
		props.put("mail.smtp.auth", "true");

		try {
			Authenticator auth = new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(FROM_EMAIL, FROM_EMAIL_PASSWORD);
				}
			};
			Session session = Session.getInstance(props, auth);
			session.setDebug(false);

			MimeMessage message = new MimeMessage(session);
            message.setContent(content, "text/html;charset=utf-8");
			message.setSubject(subject);
			message.setFrom(new InternetAddress(FROM_EMAIL));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
			message.saveChanges();

			LogUtil.log("给"+ toEmail +"开始发送");
			Transport.send(message);
			LogUtil.log("给"+ toEmail +"开始发送成功");
		} catch (Exception e) {
			System.out.println(e.toString());
			LogUtil.log("给"+ toEmail +"开始发送失败>>>" + e.getMessage());
		}
	}
}